/*
 *
 */

const ItemStatus = {
    'sold': 5, //售出
    'expired': 6, //过期
    'private': 10, //草稿
    'public': 20, //发布
    'active': 40, //活动中
};

module.exports = function(client) {
    console.log('initialization sql-item-object');

    this.getNewPublicList = function(pageSize, pageNumber, cid, callback) {
        const status = ItemStatus.public;
        if(isNaN(pageSize) || isNaN(pageNumber) || isNaN(cid)){
            return callback(ResCode.getCode(1006));
        }
        const Category = cid == 0 ? '' : ' AND cid=' + cid + ' ';

        client.query('SELECT COUNT(*) as num FROM ms_item WHERE status>:status' + Category, {
            status: status
        }, function(err, res) {
            if (err) {
                console.log(err);
                return callback(ResCode.getCode(1000));
            }
            const total = res[0].num;

            client.query('SELECT \
            id as iid, name as iName, uid, des, price, place, status, pic0, updateTime, createTime \
            FROM ms_item \
            WHERE status>=:status ' + Category + ' \
            ORDER BY updateTime DESC, id DESC \
            LIMIT :offset, :pageSize ', {
                status: status,
                pageSize: pageSize,
                offset: pageSize * pageNumber
            }, function(err, res) {
                if (err) {
                    console.log(err);
                    return callback(ResCode.getCode(1000));
                }

                return callback(ResCode.getCode(0, {
                    list: res,
                    total: total,
                    pageSize: pageSize,
                    pageNumber: pageNumber,
                    cid: cid
                }));
            });
        });
    };

    this.search = function(data, callback) {
        const status = ItemStatus.private;
        if(sql_check(data.text) || isNaN(data.pageNumber) || isNaN(data.pageSize)){
            return callback(ResCode.getCode(1006));
        }

        client.query("SELECT COUNT(*) FROM ms_item WHERE status>:status", {
            status: status,
            text: data.text
        }, function(err, res) {
            if (err) {
                console.log(err);
                return callback(ResCode.getCode(1000));
            }
            const total = res[0].num;
            //data.text = '%'+data.text.split('').join('%')+'%';
            data.text = data.text.split(' ');
            var searchText = '',
                str = '',
                i = 0;
            for (i = 0, len = data.text.length; i < len; i++) {
                str = data.text[i];
                str = str.trim();
                if (str === '') {
                    continue;
                }
                data.text[i] = str.split('').join('%');
            }
            data.text = dealArraySort(data.text, {
                name: {'name':'', 'des':''},
                add: '%',
                end: ' DESC ',
                begin: ' name LIKE BINARY '
            });

            client.query("SELECT \
            id as iid, name as iName, uid, des, price, place, status, pic0, updateTime, createTime \
            FROM ms_item \
            WHERE status>:status \
            ORDER BY "+data.text.name+", "+data.text.des+", updateTime DESC \
            LIMIT :offset, :pageSize ", {
                status: status,
                pageSize: data.pageSize,
                offset: data.pageSize * data.pageNumber
            }, function(err, res) {
                if (err) {
                    console.log(err);
                    return callback(ResCode.getCode(1000));
                }

                return callback(ResCode.getCode(0, {
                    list: res,
                    total: total,
                    pageSize: data.pageSize,
                    pageNumber: data.pageNumber
                }));
            });
        });
    };

    this.getByIid = function(iid, first, callback) {
        const status = ItemStatus.private;
        if (isNaN(iid)) {
            return callback(ResCode.getCode(1006));
        }

        client.query('SELECT \
            i.id as iid, i.name as iName, i.cid, i.uid, i.reduction, i.des, i.price, i.pic1, i.pic2, i.pic3, i.pic4, i.pic0, \
            i.place, i.status, i.updateTime, i.createTime, i.browser, \
            u.userName, u.avatar, u.telphone, u.qq \
            FROM ms_item AS i LEFT JOIN ms_user AS u ON u.id=i.uid \
            WHERE i.id=:iid AND i.status>:status', {
            status: status,
            iid: iid
        }, function(err, res) {
            if (err) {
                console.log(err);
                return callback(ResCode.getCode(1000));
            }
            if (res.length == 0) {
                return callback(ResCode.getCode(1006));
            }
            if (first === true) {
                browserItem(res[0].iid);
            }
            res[0].telphone && (res[0].telphone = res[0].telphone.substr(0, 7) + '****');
            return callback(ResCode.getCode(0, res[0]));
        });
    };

    this.add = function(data, callback) {
        data.status = ItemStatus.public;
        data.updateTime = Date.now();
        data.createTime = data.updateTime;
        data.browser = 0;
        if(sql_check(data)){
            return callback(ResCode.getCode(1006));
        }

        client.query('INSERT INTO ms_item \
            SET uid=:uid, name=:iName, des=:des, price=:price, place=:place, status=:status, \
            pic0=:pic0, pic1=:pic1, pic2=:pic2, pic3=:pic3, pic4=:pic4, \
            updateTime=:updateTime, createTime=:createTime, cid=:cid, reduction=:reduction, browser=:browser ', data, function(err, res) {
            if (err) {
                console.log(err);
                return callback(ResCode.getCode(1000));
            }
            return callback(ResCode.getCode(0, res.insertId));
        });
    };

    return this;

    function browserItem(iid) {
        client.query('UPDATE ms_item SET browser=browser+1 WHERE id=:iid', {
            iid: iid
        }, function(err, res) {
            if (err) {
                console.log(err);
            }
        });
    }
};

function dealArraySort(arr, opt) {
    for(var j in opt.name){
        opt.name[j] = getStr(arr, opt, j);
    }
    return opt.name;
}

function getStr(arr, opt, name){
    var result = '';
    for (var i = 0, len = arr.length; i < len; i++) {
        if(arr[i] === ''){
            arr.splice(i, 1);
        }
    }
    if(arr.length > 3){
        arr.length = 3;
    }
    if(arr.length === 1){
        result += name + ' LIKE BINARY \'' + opt.add + arr[0] + opt.add +'\'' + opt.end;
    }else if(arr.length === 2){
        result += name + ' LIKE BINARY \'' + opt.add + arr[0] + opt.add + arr[1] + opt.add +'\'' + opt.end;
        result += ','+name + ' LIKE BINARY \'' + opt.add + arr[1] + opt.add + arr[0] + opt.add +'\'' + opt.end;
    }else if(arr.length === 3){
        result += name + ' LIKE BINARY \'' + arr[0] + opt.add + arr[1] + opt.add + arr[2] + opt.add +'\'' + opt.end;
        result += ','+name + ' LIKE BINARY \'' + opt.add + arr[0] + opt.add + arr[2] + opt.add + arr[1] + opt.add +'\'' + opt.end;
        result += ','+name + ' LIKE BINARY \'' + opt.add + arr[1] + opt.add + arr[2] + opt.add + arr[0] + opt.add +'\'' + opt.end;
        result += ','+name + ' LIKE BINARY \'' + opt.add + arr[1] + opt.add + arr[0] + opt.add + arr[2] + opt.add +'\'' + opt.end;
        result += ','+name + ' LIKE BINARY \'' + opt.add + arr[2] + opt.add + arr[0] + opt.add + arr[1] + opt.add +'\'' + opt.end;
        result += ','+name + ' LIKE BINARY \'' + opt.add + arr[2] + opt.add + arr[1] + opt.add + arr[0] + opt.add +'\'' + opt.end;
    }
    return result;
}